
import UIKit

class TF_LivingVoteScrollView: UIScrollView, UITableViewDelegate, UITableViewDataSource {

    @objc public var DisableHorizontalScrollTag:NSInteger = 836913
    @objc public var noDisableHorizontalScrollTag:NSInteger = 836914
    //投票成功
    @objc public let voteSuccessfulHidde = UIButton()
    @objc public let list = NSMutableArray()
    @objc public var result:TFVoteData?

    //提交投票
    @objc public let submit = UIButton()
    @objc public let view1 = UIView()
    @objc public let detailView = UIView()

    //投票成功
    @objc public let voteSuccessful = UIView()
    @objc public let backButton = UIButton()
    
    @objc public let label = UILabel()
    @objc public let tableview = UITableView()
    
    @objc public var indexPathRow:NSInteger = 0
    //你的选项：B
    @objc public let optionPrompt = UILabel()
    @objc public let voteSuccessfulImageView = UIImageView()
    @objc public let voteSuccessfulLabel = UILabel()
    @objc public let imageUrlView = TF_LivingImagePreviewView()
    
    @objc public func backButtonClickUI()
    {
        //默认颜色
        self.submit.backgroundColor = UIColor(red: 223/255.0, green: 228/255.0, blue: 235/255.0, alpha: 1.0)
        self.submit.isUserInteractionEnabled = false
    }
    func voteSuccessfulHiddeClick()
    {
        UIView.animate(withDuration: 0.5) {
            
            if(self.superview != nil)
            {
                
                self.superview!.frame = CGRect(x:0, y: TalkfunSharedTools.getMainScreen().size.height, width: self.superview!.frame.size.width, height: self.superview!.frame.size.height)
                
            }
            
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
      
        self.backgroundColor = UIColor.clear
        
        self.showsVerticalScrollIndicator = false;
        self.showsHorizontalScrollIndicator = false;
        
        self.isScrollEnabled = false
        self.isPagingEnabled = true

        //投票列表
        self.addSubview(self.view1)
        self.view1.backgroundColor = UIColor(red: 245/255.0, green: 246/255.0, blue: 248/255.0, alpha: 1.0)
        
        //投票详情
        self.addSubview(self.detailView)
        self.detailView.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)

    
        //投票成功
        self.addSubview(self.voteSuccessful)
        self.voteSuccessful.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
        self.voteSuccessfulImageView.image = UIImage.init(named: "HTLive.bundle/liveingtoupiaosuccess")
        self.voteSuccessful.addSubview(self.voteSuccessfulImageView)
        
        
        self.voteSuccessfulHidde.backgroundColor = UIColor.clear
        self.addSubview(self.voteSuccessfulHidde)
       
        self.voteSuccessfulLabel.textAlignment = .center;
        self.voteSuccessfulLabel.numberOfLines = 0;
        self.voteSuccessful.addSubview(self.voteSuccessfulLabel)

        let  voteSuccessfulLabelName:NSString = "投票成功"
        //身份是学员
        let font18 = UIFont.PingFang(size: 18)
        let voteSuccessfulLabelColor = UIColor(red: 65/255.0, green: 150/255.0, blue: 235/255.0, alpha: 1.0)
        
        self.voteSuccessfulLabel.attributedText = NSMutableAttributedString.getAttributed(string: voteSuccessfulLabelName as String, font: font18, foregroundColor: voteSuccessfulLabelColor);
        self.voteSuccessfulLabel.textColor = voteSuccessfulLabelColor
       
        
        self.detailView.addSubview(self.backButton)
        self.backButton.setImage(UIImage.init(named: "HTLive.bundle/backlisttoupiao"), for: .normal)
     
        self.label.numberOfLines = 0;
         self.detailView.addSubview(self.label)
        self.label.textColor = UIColor(red: 20/255.0, green: 23/255.0, blue: 26/255.0, alpha: 1.0)
       
        self.tableview.delegate = self;
        self.tableview.dataSource = self;
        self.detailView.addSubview(self.tableview)
        self.tableview.backgroundColor = UIColor.clear
        self.tableview.separatorStyle = .none;

 
        //默认颜色
        self.backButtonClickUI()
        self.submit.layer.cornerRadius = 4;
        self.detailView.addSubview(self.submit)
        self.submit.setTitle("投票", for: .normal)
        self.submit.titleLabel!.font = UIFont.PingFang(size: 17)
        self.submit.setTitleColor(UIColor(red:255/255.0, green:255/255.0, blue:255/255.0, alpha: 1.0), for: .normal)
        self.submit.isHidden = true
        
        self.detailView.addSubview(self.optionPrompt)
        self.optionPrompt.font =  UIFont.PingFang(size: 16)
        self.optionPrompt.textColor = UIColor(red: 65/255.0, green: 150/255.0, blue: 235/255.0, alpha: 1.0)
        

        self.optionPrompt.numberOfLines = 0;
        
        self.tableview.register(TF_LivingVoteScrollViewImageCell.self, forCellReuseIdentifier: "TF_LivingVoteScrollViewImageCell")
        
        self.tableview.register(TF_LivingVoteScrollViewCell.self, forCellReuseIdentifier: "TF_LivingVoteScrollViewCell")

    }
    override func layoutSubviews() {
        super.layoutSubviews()
        
        self.contentSize = CGSize(width: self.frame.size.width * 3, height: self.frame.size.height)
     
        self.view1.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)

        self.detailView.frame = CGRect(x: self.frame.size.width, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        
        
        self.voteSuccessful.frame =  CGRect(x: self.frame.size.width * 2, y: self.frame.size.height - 246, width: self.frame.size.width, height: 246)
        

        self.voteSuccessful.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)

        self.voteSuccessful.layer.shadowColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0).cgColor
  
        self.voteSuccessful.layer.shadowOffset = CGSize(width: 0, height: -2)

        self.voteSuccessful.layer.shadowRadius = 12
        self.voteSuccessful.layer.shadowOpacity = 1
        self.voteSuccessful.layer.cornerRadius = 10
        
        
        self.voteSuccessfulImageView.frame = CGRect(x: (self.voteSuccessful.frame.size.width - 200)/2, y: (self.voteSuccessful.frame.size.height - 200)/2, width: 200, height: 137)

        self.voteSuccessfulHidde.frame = CGRect(x: self.frame.size.width * 2, y: 0, width: self.frame.size.width, height: self.frame.size.height - self.voteSuccessful.frame.size.height)
        
        self.voteSuccessfulLabel.frame = CGRect(x: 0, y: 157, width: self.voteSuccessful.frame.size.width, height: 25)
        

        self.backButton.frame = CGRect(x: self.frame.size.width - 32 - 6, y: 6, width: 32, height: 32)

        
        self.label.frame = CGRect(x: 12, y: 61, width: self.frame.size.width - 24, height: 22)
      
        
        self.tableview.frame = CGRect(x: 21, y: 103, width:  self.frame.size.width - 21 - 23, height: self.frame.size.height - 100 - 118)
    
        
        var submitY:CGFloat = 68 - 32
        if (self.isNotchScreen) {
                submitY = 68;
        }

        self.submit.frame = CGRect(x: (self.frame.size.width - 180)/2, y: self.frame.size.height - 40 - submitY, width: 180, height: 40)

        
        self.optionPrompt.frame = CGRect(x: 12, y: self.frame.size.height - 46 - 22, width: self.frame.size.width - 24, height: 22)

    }
  @objc public func voteDetail(result:TFVoteData)
    {
        self.result = result
        //已经投票
        if (result.voted || result.info.endTime != "0") {
            self.submit.isHidden = true
        }else
        {
            self.submit.isHidden = false
        }
        
        var labelStr:NSString = "【"
        //单选
        if (result.optional == 1 ) {
            labelStr = (labelStr as String) + "单选" as NSString
        
        }else{
            labelStr = (labelStr as String) + "多选" as NSString
        }
        labelStr = (labelStr as String) + "】" as NSString

        var str:NSString = result.info.title as NSString
        
        let imageUrl:NSString = result.info.imageUrl as NSString
        //图片模式是标签
        if (imageUrl.length > 0) {
            str = result.info.label as NSString
        }else{
        //文字模式是主题
            str = result.info.title as NSString
        }
        
        labelStr = (labelStr as String) + (str as String) as NSString

        
        self.label.attributedText = NSMutableAttributedString.getAttributed(string: labelStr as String, font: UIFont(name: "PingFang SC", size: 16)!, foregroundColor: UIColor(red: 20/255.0, green: 23/255.0, blue: 26/255.0,alpha:1))
        
        self.list.removeAllObjects()
        self.list.addObjects(from: result.opList as! [Any])

        self.tableview.tag = self.DisableHorizontalScrollTag;
        
        self.tableview.reloadData()
        self.tableview.flashScrollIndicators()
        //用户有选择答案了
        if (result.userList.count > 0 ) {
            var content:NSString = "";
            let userModel:TFVoteNewUser = self.result!.userList[0] as! TFVoteNewUser
            
            for i in stride(from: 0, to: userModel.option.count ,by: 1) {
                
                let inx:NSString = userModel.option[i] as! NSString
                
                let prefix = TalkfunSharedTools.asciiBytesToString(inx: inx.integerValue)
                
                content = (content as String) + prefix as NSString
                
            }

            self.optionPrompt.text = "你的选项：" + (content as String)
            
        }else   if (result.isShow ) {
            var content:NSString = ""
            for i in stride(from: 0, to: result.info.answer.count ,by: 1) {
                let inx:NSString = result.info.answer[i] as! NSString
                let prefix = TalkfunSharedTools.asciiBytesToString(inx: inx.integerValue)
                content = (content as String) + prefix as NSString
            }

         
            self.optionPrompt.text = ("正确选项：" as String) + (content as String)
        }else{
            self.optionPrompt.text = ""
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    //多少组
    func numberOfSections(in tableView: UITableView) -> Int {
        if (self.result != nil) {
            //图形模式
            let imageUrl:NSString = self.result!.info.imageUrl as NSString
            
            //图形模式
              if (imageUrl.length > 0) {
                  
                  return 2;
              }
              
        }
          return 1;

    }

    func getimageUrl()->NSString{
        if (self.result != nil) {
            return self.result!.info.imageUrl as NSString;
        }
        return ""
    }
    //每组的数据
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       
        
        if (self.getimageUrl().length > 0) {
            
            if (section == 0) {
                return 1;
            }else{
                return self.list.count;
            }
        }

    return self.list.count;
    }
    /**
    * 告诉tableView每一行显示什么内容（tableView的每一行都是UITableViewCell）
    */
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let imageUrl:NSString = self.getimageUrl()

        if (indexPath.section == 0 && imageUrl.length > 0) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TF_LivingVoteScrollViewImageCell") as! TF_LivingVoteScrollViewImageCell
            
            cell.selectionStyle = .none
          
            let url:URL? = URL.init(string: imageUrl as String)
            cell.imageUrlView .sd_setImage(with: url, completed: nil)


           return cell;
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "TF_LivingVoteScrollViewCell") as! TF_LivingVoteScrollViewCell
            cell.selectionStyle = .none
            

            let model:TFOp = self.list[indexPath.row] as! TFOp
            cell.tag = indexPath.row;
            cell.cellWidth = self.frame.size.width;
            
            cell.model = model;
            //学员选择的答案
            if (self.result!.userList.count > 0  ) {
                
                let userModel:TFVoteNewUser = self.result!.userList[0] as! TFVoteNewUser
                for i in stride(from: 0, to: userModel.option.count ,by: 1) {
                    let inx = userModel.option[i] as! NSString
                    if inx.integerValue == indexPath.row {
                        
                        cell.view.backgroundColor = UIColor(red: 235/255.0, green: 245/255.0, blue: 255.0/255.0, alpha: 1.0)
                        
                        cell.opLabel.textColor = UIColor(red: 65/255.0, green: 150/255.0, blue: 235/255.0, alpha: 1.0)
                    }
                    
                }

         
            }
            
            //公布答案
            if (self.result!.isShow) {
                
                cell.quantity.isHidden = false
                cell.percentage.isHidden = false
            }else{
                cell.quantity.isHidden = true
                //百分比
                cell.percentage.isHidden = true
            }
                

          
           return cell;
        }
        
        
      
    }
    
    // 设置cell高度
       func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
           //图形模式
           let imageUrl:NSString = self.getimageUrl()
           if (indexPath.section == 0 && imageUrl.length > 0) {
               return ( self.frame.size.width - 21 - 23) *  (9.0/16.0);
           }
           
         return 40 + 15 ;
       }
    
    // 选中cell后执行此方法
     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         if (self.result != nil) {
         //已经投票
         if (self.result!.voted || self.result!.info.endTime != "0" ) {
             return;
         }
         }
         //图形模式
         let imageUrl:NSString = self.getimageUrl()
         if (indexPath.section == 0 && imageUrl.length > 0) {
             
             let keyWindow = TalkfunSharedTools.keyWindow()
           
                 keyWindow.addSubview(self.imageUrlView)
             
             
            
            self.imageUrlView.frame =  TalkfunSharedTools.getMainScreen()
            self.imageUrlView.layoutSubviewsUI(imageUrl: imageUrl)
          
            
             return;
         }
         //单选
         if ( self.result != nil && self.result!.optional == 1 ) {
             
             let model = self.list[indexPath.row] as! TFOp;
             
             for i in stride(from: 0, to:self.list.count ,by: 1) {
                 let model22 = self.list[i] as! TFOp;
                     model22.selected = false
             }
         
             let arr:NSArray = tableView.indexPathsForVisibleRows! as NSArray
           
             
             for i in stride(from: 0, to:arr.count ,by: 1) {
                 let indexPath11 = arr[i] as! IndexPath
                 UIView.setAnimationsEnabled(false)
                 tableView.reloadRows(at: [indexPath11], with: .none)
                 UIView.setAnimationsEnabled(true)
             }
             
             if (self.indexPathRow != indexPath.row) {
                 
                 self.indexPathRow = indexPath.row;
                 
                 model.selected = true
                 // 蓝色
                 self.submit.backgroundColor = UIColor(red: 65/255.0, green: 150/255.0, blue: 235/255.0, alpha: 1.0)
                 
             
                 self.submit.isUserInteractionEnabled = true
             }else{
               
                 model.selected = !model.selected;
                 if (model.selected) {
                     // 蓝色
                     self.submit.backgroundColor = UIColor(red: 65/255.0, green: 150/255.0, blue: 235/255.0, alpha: 1.0)
                     self.submit.isUserInteractionEnabled = true
                 }else{
                     //默认颜色
                     self.backButtonClickUI()
                 }
             }
            
             UIView.setAnimationsEnabled(false)
             tableView.reloadRows(at: [indexPath], with: .none)
           
             UIView.setAnimationsEnabled(true)
         }else{
             var count:NSInteger = 0
             for i in stride(from: 0, to:self.list.count ,by: 1) {
                 let model = self.list[i] as! TFOp
                 if (model.selected == true) {
                     count = count + 1;
                 }
             }
         
             let model = self.list[indexPath.row] as! TFOp
             if (self.result!.optional > 1 ) {
                 model.selected = !model.selected;
                
             }else if( self.result!.optional == 1 ) {
                 if (count == 1 ) {
                     model.selected = false
                 }else{
                     model.selected = true
                 }
             }
             
             let cell = tableView.cellForRow(at: indexPath) as! TF_LivingVoteScrollViewCell
  
             cell.model = model;
             

             count = 0;
             
             for i in stride(from: 0, to:self.list.count ,by: 1) {
                 let model = self.list[i] as! TFOp
                 if (model.selected == true) {
                     count = count + 1;
                 }
             }
          
             //判断是否是多选           判断选 了几个
             if (self.result!.optional >= 1 && count > 0) {
                 // 蓝色
                 self.submit.backgroundColor = UIColor(red: 65/255.0, green: 150/255.0, blue: 235/255.0, alpha: 1.0)
                 self.submit.isUserInteractionEnabled = true
             }

             else{
                 //默认颜色
                 self.backButtonClickUI()
             }
            
         }
     }
}
